package com.hmall.search.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.api.client.ItemClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.search.domain.dto.PageDTO;
import com.hmall.common.utils.BeanUtils;
import com.hmall.common.utils.CollUtils;
import com.hmall.search.domain.dto.ItemDoc;
import com.hmall.search.domain.po.Item;
import com.hmall.search.domain.query.ItemPageQuery;
import com.hmall.search.service.ISearchService;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-11-09 15:47
 **/
@Service
@RequiredArgsConstructor
public class SearchServiceImpl  implements ISearchService {
    private final ItemClient itemClient;
    private final RestHighLevelClient restHighLevelClient;
    /**
     * 搜索商品
     *
     * @param itemPageQuery
     * @return
     */
    @Override
    public PageDTO<ItemDTO> search(ItemPageQuery itemPageQuery) {
        String key = itemPageQuery.getKey();
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("items");
        // 1.构建查询条件
        SearchSourceBuilder searchSourceBuilder = getSearchSourceBuilder(itemPageQuery, key);
        // 排序
        String sortBy = itemPageQuery.getSortBy();
        if (StrUtil.isNotEmpty(sortBy)){
            searchSourceBuilder.sort(itemPageQuery.getSortBy(), itemPageQuery.getIsAsc() ? SortOrder.ASC : SortOrder.DESC);
        }
        // 分页
        // 默认从第1页页码开始
        Integer pageNo = itemPageQuery.getPageNo();
        // 默认每页10条数据
        Integer pageSize = itemPageQuery.getPageSize();
        searchSourceBuilder.from((pageNo-1)*pageSize);
        searchSourceBuilder.size(pageSize);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(searchSourceBuilder);
        // 2.创建分页对象
        PageDTO<ItemDTO> pageDTO = new PageDTO<>();
        // 3.查询
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHits = searchResponse.getHits();
            // 获取总条数
            long total = searchHits.getTotalHits().value;
            SearchHit[] hits = searchHits.getHits();
            // 创建集合收集数据
            List<ItemDTO> itemDTOS = CollUtils.newArrayList();
            // 遍历结果
            for (SearchHit searchHit : hits) {
                String sourceAsString = searchHit.getSourceAsString();
                ItemDoc itemDoc = JSONUtil.toBean(sourceAsString, ItemDoc.class);
                // 高亮
                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                if (highlightFields != null){
                    HighlightField highlightField = highlightFields.get("name");
                    if (highlightField != null){
                        Text[] fragments = highlightField.fragments();
                        String name = fragments[0].toString();
                        itemDoc.setName(name);
                    }
                }
                ItemDTO itemDTO = BeanUtils.copyBean(itemDoc, ItemDTO.class);
                itemDTOS.add(itemDTO);
            }
            pageDTO.setTotal(total);
            pageDTO.setList(itemDTOS);
        } catch (IOException e) {
            System.out.println("查询失败！");
            e.printStackTrace();
            return null;
        }
        // 4.返回结果
        return pageDTO;
    }

    /**
     * 构建查询商品
     * @param itemPageQuery
     * @param key
     * @return
     */
    private SearchSourceBuilder getSearchSourceBuilder(ItemPageQuery itemPageQuery, String key) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        if (StrUtil.isBlank(key)){
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            // 查询所有商品
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            // 品牌
            String brand = itemPageQuery.getBrand();
            if (StrUtil.isNotEmpty(brand)){
                boolQueryBuilder.filter(QueryBuilders.termQuery("brand",brand));
            }
            // 分类
            String category = itemPageQuery.getCategory();
            if (StrUtil.isNotEmpty(category)){
                boolQueryBuilder.filter(QueryBuilders.termQuery("category",category));
            }
            // 最大价格和最小价格
            Integer minPrice = itemPageQuery.getMinPrice();
            Integer maxPrice = itemPageQuery.getMaxPrice();
            if (minPrice != null && maxPrice != null){
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice).gte(minPrice));
            }
            searchSourceBuilder.query(boolQueryBuilder);
            return searchSourceBuilder;
        }
        else {
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //查询是否有筛选条件
            // 名字
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", key));
            // 品牌
            String brand = itemPageQuery.getBrand();
            if (StrUtil.isNotEmpty(brand)){
                boolQueryBuilder.filter(QueryBuilders.termQuery("brand",brand));
            }
            // 分类
            String category = itemPageQuery.getCategory();
            if (StrUtil.isNotEmpty(category)){
                boolQueryBuilder.filter(QueryBuilders.termQuery("category",category));
            }
            // 最大价格和最小价格
            Integer minPrice = itemPageQuery.getMinPrice();
            Integer maxPrice = itemPageQuery.getMaxPrice();
            if (minPrice != null && maxPrice != null){
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice).gte(minPrice));
            }
            searchSourceBuilder.query(boolQueryBuilder);
        }
        return searchSourceBuilder;
    }

    /**
     * 初始化ES
     */
    @Override
    public void initES() {
        // 1.从数据库中获取商品数据
        int pageNum = 1;
        while (true){
            List<ItemDTO> itemDTOS = itemClient.queryItemByPage(pageNum, 1000);
            // 判断是否为空
            if (CollUtils.isEmpty(itemDTOS)){
                return;
            }
            // 2.批量插入
            BulkRequest bulkRequest = new BulkRequest();

            for (ItemDTO itemDTO : itemDTOS) {
                // 封装
                ItemDoc itemDoc = BeanUtils.copyBean(itemDTO, ItemDoc.class);
                IndexRequest indexRequest = new IndexRequest("items");
                indexRequest.id(itemDoc.getId());
                indexRequest.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
            try {
                //初始化 ES
                restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            pageNum++;
        }

    }

    /**
     * 从ES获取商品过滤条件
     *
     * @param itemPageQuery
     * @return
     */
    @Override
    public Map<String, List<String>> filters(ItemPageQuery itemPageQuery) {
        String key = itemPageQuery.getKey();
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("items");
        // 1.构建查询条件
        SearchSourceBuilder searchSourceBuilder = getSearchSourceBuilder(itemPageQuery, key);
        searchSourceBuilder.aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(50));
        searchSourceBuilder.aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(50));
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            Aggregations aggregations = searchResponse.getAggregations();
            // 处理品牌
            List<String> brands = new ArrayList<>();
            Terms brandAggTerms = aggregations.get("brandAgg");
            List<? extends Terms.Bucket> buckets = brandAggTerms.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                String brandName = bucket.getKeyAsString();
                brands.add(brandName);
            }
            // 处理分类
            List<String> categoryList = new ArrayList<>();
            Terms categoryAggTerms = aggregations.get("categoryAgg");
            List<? extends Terms.Bucket> buckets1 = categoryAggTerms.getBuckets();
            for (Terms.Bucket bucket : buckets1) {
                String categoryName = bucket.getKeyAsString();
                categoryList.add(categoryName);
            }
            Map<String, List<String>> listMap = Map.of("brand", brands, "category", categoryList);
            return listMap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
